﻿#if ENABLE_HCLR

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using UnityEngine;
using UnityEditor;
using Core;
using System.Text;

public class HybridClrEditor
{
    public static void CopyMetadata()
    {
        if (!HybridCLR.Editor.SettingsUtil.Enable)
            return;

        var dllFiles = GetFilePaths();

        // 拷贝资源到steamingAsset目录
        var streamingPath = $"{Application.streamingAssetsPath}/{GameConst.HCLR_METADATA_PATH}";
        if (Directory.Exists(streamingPath))
            Directory.Delete(streamingPath, true);
        Directory.CreateDirectory(streamingPath);

        var configBuilder = new StringBuilder();

        foreach (var dllPair in dllFiles)
        {
            var key = dllPair.Key;
            var path = dllPair.Value;

            var bytes = File.ReadAllBytes(path);

            // 压缩
            bytes = Utils.Compress(bytes);

            var destFileName = $"{streamingPath}/{key}";
            File.WriteAllBytes(destFileName, bytes);

            configBuilder.AppendLine(key);
        }

        var configPath = $"{streamingPath}/{GameConst.HCLR_METADATA_CONFIG_NAME}";
        File.WriteAllText(configPath, configBuilder.ToString());

        Debug.Log("CopyMetadataToStreaming complete!");
    }

    private static Dictionary<string, string> GetFilePaths()
    {
        var result = new Dictionary<string, string>();

        var hclrCsPath = $"Assets/HybridCLRGenerate/AOTGenericReferences.cs";
        var content = File.ReadAllText(hclrCsPath);
        var assembliesReg = new Regex("// {{ AOT assemblies([\\s\\S]+?)// }}");
        var assembliesMatch = assembliesReg.Match(content);
        if (!assembliesMatch.Success)
        {
            Debug.LogError("匹配不到assemblies");
            return result;
        }

        var assembliesContent = assembliesMatch.Groups[1].Value;
        var dllReg = new Regex("{([\\s\\S]+?)}");
        var dllMatch = dllReg.Match(assembliesContent);
        if (!dllMatch.Success)
        {
            Debug.LogError("匹配不到dll");
            return result;
        }

        var dllContent = dllMatch.Groups[1].Value.Trim();
        var dllLines = dllContent.Split(',');

        var generateMetadataPath = $"HybridCLRData/AssembliesPostIl2CppStrip/{EditorUserBuildSettings.activeBuildTarget}";
        foreach (var item in dllLines)
        {
            var dllName = item.Trim().Replace("\"","");
            if (string.IsNullOrEmpty(dllName))
                continue;

            var dllFullPath = $"{generateMetadataPath}/{dllName}";
            result.Add($"{dllName.ToLower()}.bytes", dllFullPath);
        }

        return result;
    }

    private static HotfixInfo GetHotfixDlls()
    {
        var result = new HotfixInfo();

        var dllNames = HybridCLR.Editor.SettingsUtil.HotUpdateAssemblyNamesIncludePreserved;

        var generateDllPath = $"HybridCLRData/HotUpdateDlls/{EditorUserBuildSettings.activeBuildTarget}";

        foreach (var dllName in dllNames)
        {
            var dllFullPath = $"{generateDllPath}/{dllName}.dll";
            var assetKey = $"hclr/{dllName.ToLower()}.dll.bytes";
            result.assetKeyToPath.Add(assetKey, dllFullPath);
            result.assetKeys.Add(assetKey);
        }

        return result;
    }

    public class HotfixInfo
    {
        public Dictionary<string, string> assetKeyToPath = new Dictionary<string, string>();
        public List<string> assetKeys = new List<string>();
    }

    public static void CheckHclrHotfixDlls()
    {
        if (!HybridCLR.Editor.SettingsUtil.Enable)
            return;

        // 比较HCLR热更程序集
        var hotfixDlls = GetHotfixDlls();
        foreach (var hotfixPair in hotfixDlls.assetKeyToPath)
        {
            var dllKey = hotfixPair.Key;
            var dllPath = hotfixPair.Value;

            AssetBundleEditor.CompareFileByCrc32(dllPath, dllKey);
        }

        AssetBundleEditor.newLaunchFiles.hclrDlls = hotfixDlls.assetKeys;
    }
}

#endif